﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace DTcms.Common
{
    public class SitemapXml
    {
        private const string Xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9";
        private const string XmlnsXsi = "http://www.w3.org/2001/XMLSchema-instance";
        private const string XsiSchemaLocation = "http://www.sitemaps.org/schemas/sitemap/0.9  http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd";

        #region Xml
        /// <summary>  
        /// 生成SiteMap地图  
        /// </summary>  
        /// <param name="siteMaps">需要生成的 对象列表</param>  
        /// <param name="saveFileName">设置文件保存名称</param>  
        /// <param name="changefreq">更新周期</param>  
        /// <param name="savePath">xml文件保存路径</param>  
        /// <returns></returns>  
        public static bool CreateSiteMapXml(List<PageInfo> siteMaps, string savePath = "/", string saveFileName = "sitemap", string changefreq = "weekly")
        {
            //保存创建好的XML文档  
            string filename = saveFileName + ".xml";
            string path = Utils.GetMapPath(savePath) + filename;

            //先创建XML,返回路径  
            var xmldoc = new XmlDocument();
            //加入XML的声明段落,<?xml version="1.0" encoding="gb2312"?>  
            XmlDeclaration xmldecl = xmldoc.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmldoc.AppendChild(xmldecl);

            //加入一个根元素  
            XmlNode xmlelem = xmldoc.CreateElement("", "urlset", "");
            //添加属性  
            XmlAttribute attr = xmldoc.CreateAttribute("xmlns");
            attr.Value = Xmlns;
            if (xmlelem.Attributes != null) xmlelem.Attributes.SetNamedItem(attr);

            attr = xmldoc.CreateAttribute("xmlns:xsi");
            attr.Value = XmlnsXsi;
            if (xmlelem.Attributes != null) xmlelem.Attributes.SetNamedItem(attr);

            attr = xmldoc.CreateAttribute("xsi:schemaLocation");
            attr.Value = XsiSchemaLocation;
            if (xmlelem.Attributes != null) xmlelem.Attributes.SetNamedItem(attr);

            xmldoc.AppendChild(xmlelem);
            string lastmod = DateTime.Now.ToString("yyyy-MM-dd");
            for (int i = 0; i < siteMaps.Count; i++)
            {
                XmlNode root = xmldoc.SelectSingleNode("urlset");//查找<urlset>   
                if (root == null)
                {
                    //加入一个根元素  
                    xmlelem = xmldoc.CreateElement("", "urlset", "");
                    //添加属性  
                    attr = xmldoc.CreateAttribute("xmlns");
                    attr.Value = Xmlns;
                    if (xmlelem.Attributes != null) xmlelem.Attributes.SetNamedItem(attr);

                    attr = xmldoc.CreateAttribute("xmlns:xsi");
                    attr.Value = XmlnsXsi;
                    if (xmlelem.Attributes != null) xmlelem.Attributes.SetNamedItem(attr);

                    attr = xmldoc.CreateAttribute("xsi:schemaLocation");
                    attr.Value = XsiSchemaLocation;
                    if (xmlelem.Attributes != null) xmlelem.Attributes.SetNamedItem(attr);

                    xmldoc.AppendChild(xmlelem);
                    i = 0;
                    continue;
                }
                XmlElement xe1 = xmldoc.CreateElement("url");//创建一个<url>节点   

                XmlElement xmlelem1 = xmldoc.CreateElement("", "loc", "");
                XmlText xmltext = xmldoc.CreateTextNode(siteMaps[i].loc);
                xmlelem1.AppendChild(xmltext);
                xe1.AppendChild(xmlelem1);

                xmlelem1 = xmldoc.CreateElement("", "priority", "");
                xmltext = xmldoc.CreateTextNode(siteMaps[i].priority);
                xmlelem1.AppendChild(xmltext);
                xe1.AppendChild(xmlelem1);

                xmlelem1 = xmldoc.CreateElement("", "lastmod", "");
                xmltext = xmldoc.CreateTextNode(lastmod);
                xmlelem1.AppendChild(xmltext);
                xe1.AppendChild(xmlelem1);

                xmlelem1 = xmldoc.CreateElement("", "changefreq", "");
                xmltext = xmldoc.CreateTextNode(changefreq);
                xmlelem1.AppendChild(xmltext);
                xe1.AppendChild(xmlelem1);

                root.AppendChild(xe1);//添加到<urlset>节点中   
            }
            try
            {
                //然后在保存到源位置  
                xmldoc.AppendChild(xmlelem);
                xmldoc.Save(path);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 生成SiteMap字符串
        /// </summary>
        /// <returns></returns>
        public static string GenerateSiteMapString(List<PageInfo> url)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?> ");
            sb.AppendLine("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");
            string linkurl = string.Empty;
            foreach (PageInfo pi in url)
            {
                linkurl = pi.loc.Replace("&", "&amp;");
                sb.AppendLine("<url>");
                sb.AppendLine(string.Format("<loc>{0}</loc>", linkurl));
                sb.AppendLine(string.Format("<lastmod>{0}</lastmod> ", pi.lastmod.ToString("yyyy-MM-dd")));
                sb.AppendLine(string.Format("<changefreq>{0}</changefreq> ", pi.changefreq));
                sb.AppendLine(string.Format("<priority>{0}</priority> ", pi.priority));
                sb.AppendLine("</url>");
            }

            sb.AppendLine("</urlset>");
            return sb.ToString();
        }
        #endregion

        #region Html
        /// <summary>
        /// 生成Html
        /// </summary>
        /// <returns></returns>
        public static bool GenerateSiteMapHTML(List<PageInfo> url, string savePath = "/", string saveFileName = "sitemap")
        {
            //保存创建好的XML文档  
            string filename = saveFileName + ".html";
            string path = savePath + filename;

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<html xmlns=\"http://www.w3.org/1999/xhtml\"> ");
            sb.AppendLine("<head>");
            sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />");
            sb.AppendLine("<title>站点地图</title>");
            sb.AppendLine("</head>");
            sb.AppendLine("<body>");
            string linkurl = string.Empty;
            foreach (PageInfo pi in url)
            {
                linkurl = pi.loc.Replace("&", "&amp;");
                sb.AppendLine(string.Format("<a href=\"{0}\" title=\"{1}\">{1}</a><br/>", linkurl, pi.title));
            }
            sb.AppendLine("</body>");
            sb.AppendLine("</html>");

            try
            {
                SaveSiteMap(path, sb.ToString());
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        #endregion

        #region txt
        /// <summary>
        /// 生成txt
        /// </summary>
        /// <returns></returns>
        public static bool GenerateSiteMapTXT(List<PageInfo> url, string savePath = "/", string saveFileName = "sitemap")
        {
            //保存创建好的XML文档  
            string filename = saveFileName + ".txt";
            string path = savePath + filename;

            StringBuilder sb = new StringBuilder();
            string linkurl = string.Empty;
            foreach (PageInfo pi in url)
            {
                linkurl = pi.loc.Replace("&", "&amp;");
                sb.AppendLine(linkurl);
            }

            try
            {
                SaveSiteMap(path, sb.ToString());
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name=”FilePath”>路径</param>
        public static void SaveSiteMap(string FilePath, List<PageInfo> url)
        {
            FileHelper.WriteFile(FilePath, GenerateSiteMapString(url));
        }

        public static void SaveSiteMap(string FilePath, string Content)
        {
            FileHelper.WriteFile(FilePath, Content);
        }
    }

    public class PageInfo
    {
        /// <summary>  
        /// 标题  
        /// </summary>  
        public string title { get; set; }

        /// <summary>  
        /// 链接地址  
        /// 如：http://news.chinahbnet.com  
        /// </summary>  
        public string loc { get; set; }

        /// <summary>  
        /// 网页权重  
        /// 0.1 - 1  
        /// </summary>  
        public string priority { get; set; }

        /// <summary>  
        /// 最后更新时间  
        /// 2014-08-19  
        /// </summary>  
        public DateTime lastmod { get; set; }

        /// <summary>  
        /// 更新周期  
        /// always  经常  
        /// hourly  每小时  
        /// daily   每天  
        /// weekly  每周  
        /// monthly 每月  
        /// yearly  每年  
        /// never   从不  
        /// </summary>  
        public string changefreq { get; set; }
    }
}
